package com.hantang.web.json.handlers;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson;
import com.hantang.web.config.JsonConfig;
import com.hantang.web.dao.ArticleDao;
import com.hantang.web.data.ArticleData;
import com.hantang.web.json.ds.Article;
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.res.ArticleInfoRes;

public class QueryUserPubArticlesHandler extends AbstractHandler {



		static String META_INFO = "content max size is" + JsonConfig.getInstance().articleInfoContentSize;
		private static Logger logger = Logger.getLogger(QueryArticlesHandler.class);
		@Override
		public String doService(Request req, Response resp) throws Exception {

			String username = req.getParameter("username");
			String slastUpdatetime = req.getParameter("lastupdatetime");
			String scount = req.getParameter("count");
			
			String sret = handleServlet(username, slastUpdatetime, scount);
			
			return sret;
		}

		public static String handleServlet(String username, String slastUpdatetime,
				String scount) {
			Date lastUpdateTime = new Date(Long.MAX_VALUE);
			if(slastUpdatetime != null)
			{
				lastUpdateTime = new Date(Long.valueOf(slastUpdatetime));
			}
			
			int count = 10;
			if(scount != null){
				count = Integer.valueOf(scount.trim());
			}
			ArticleInfoRes resData = new ArticleInfoRes();
			if(username != null){
				List<Article> articles = handle(username, lastUpdateTime, count, true);
				resData.setData(articles);
				resData.setMeta(new MetaData(MetaData.META_DATA_SUCCESS_CODE, META_INFO));
			}else{
				resData.setMeta(new MetaData(MetaData.META_DATA_ERROR_PARA, "Failed"));
			}
			Gson gson = new Gson();
			String sret = gson.toJson(resData);
			return sret;
		}

		public static List<Article> handle(String username, Date lasttime, int count, boolean isOnlyPub)
		{
			logger.info("handle, lasttime:" + lasttime + " count:" + count);
			List<Article> articles = new ArrayList<Article>();
			ArticleDao dao = new ArticleDao();
			List<ArticleData> datas = dao.queryDatasByUser(lasttime, count, username, isOnlyPub);
			if(datas != null){
				for(ArticleData data : datas)
				{
					Article article = Article.convertData2Json(data, JsonConfig.getInstance().articleInfoContentSize);
					articles.add(article);
				}
				logger.info("handle, lasttime:" + lasttime + " return size:" + articles.size());
			}else{
				articles = null;
				logger.error("handle, articles  is null");
			}
			return articles;		
		}
		

}
